package org.huatek.anders.filter;

import org.huatek.anders.constants.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author anders
 * @date 2018-12-21 10:14
 **/
public class AbstractFilter implements Filter {
    private AtomicInteger requestCount = new AtomicInteger(0);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        ///HttpServletRequest request = (HttpServletRequest) servletRequest;
        requestCount.incrementAndGet();
        if(requestCount.intValue() <= Constants.MAX_REQUEST_COUNT) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("当前访问数量较多，请稍后访问……");
        }
        requestCount.decrementAndGet();
    }

    @Override
    public void destroy() {

    }
}
